package poi;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellReference;

import java.io.FileOutputStream;
import java.util.Date;

public class Test {
    public static void main(String[] args) throws Exception{
        Workbook w1=new HSSFWorkbook();
        CreationHelper creationHelper=w1.getCreationHelper();
        CellStyle cellStyle=w1.createCellStyle();
        cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("m/d/yy h:mm"));


        //创建新sheet
        Sheet sheet1=w1.createSheet("new sheet");
        Sheet sheet2= w1.createSheet("second sheet");

        //create new row
        Row row=sheet1.createRow((short)0);

        //create new cell
        Cell cell=row.createCell(0);
        cell.setCellValue(new Date());
        cell.setCellStyle(cellStyle);

        row.createCell(1).setCellValue(new Date());
        row.createCell(2).setCellValue(creationHelper.createRichTextString("This is a string"));
        row.createCell(3).setCellValue(true);
        row.createCell(4).setCellType(CellType.ERROR);


        /**for (Sheet sheet :w1) {
            for (Row rows :sheet) {
                for (Cell cell1 :rows) {
                    System.out.println(cell1);
                }
            }
        }*/

        DataFormatter formatter=new DataFormatter();
        for (Row r:sheet1){
            for (Cell c :r) {
                CellReference reference=new CellReference(r.getRowNum(),c.getColumnIndex());
                System.out.print(reference.formatAsString());
                System.out.print(" - ");

                //get the text thar appears in the cell by getting the cell value and applying any data foramts
                String text=formatter.formatCellValue(c);
                System.out.print(text+"\t");

                switch (c.getCellTypeEnum()) {
                    case STRING:
                        System.out.println(c.getRichStringCellValue().getString());
                        break;
                    case NUMERIC:
                        if (DateUtil.isCellDateFormatted(c)) {
                            System.out.println(c.getDateCellValue());
                        } else {
                            System.out.println(c.getNumericCellValue());
                        }
                        break;
                    case BOOLEAN:
                        System.out.println(c.getBooleanCellValue());
                        break;
                    case FORMULA:
                        System.out.println(c.getCellFormula());
                        break;
                    case BLANK:
                        System.out.println();
                        break;
                    default:
                        System.out.println();
                }
            }

        }



        FileOutputStream fot=new FileOutputStream("workbook.xls");
        w1.write(fot);
        fot.close();

    }


}
